#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <kwindowsystem.h>

#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusConnectionInterface>

#include <iostream>

#include "kpowerboxserver.h"

using namespace std;


int main(int argc, char *argv[])
{
	cout << "KPowerboxServer" << endl;

	KAboutData aboutData("kpowerboxserver", 0, ki18n("KPowerboxServer"),
	                     "1.0",
	                     ki18n("Server which displays powerboxes for Capacium" ),
	                     KAboutData::License_BSD,
	                     ki18n("(c) 2009 Jonathan Anderson"));

	aboutData.setProgramIconName("system-run");


	KCmdLineArgs::init(argc, argv, &aboutData);

	KCmdLineOptions cmdLineOptions;
	cmdLineOptions.add("name <service-name>",
	                   ki18n("Name of the service"),
	                   "org.freebsd.capsicum.kde");

	KCmdLineArgs::addCmdLineOptions(cmdLineOptions);


	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
	QString serviceName = args->getOption("name");


	KApplication app;

	if(!QDBusConnection::sessionBus().isConnected())
	{
		cerr << "Can't connect to the D-Bus session bus" << endl;
		return 1;
	}

	QDBusConnection dbus = QDBusConnection::sessionBus();
	if(dbus.registerService(serviceName))
		cout << "Registered " << serviceName.toStdString();

	else
	{
		cerr << "The Capsicum service has already been registered" << endl;
		return 1;
	}

	KPowerBoxServer kpbserv;
	QString path = "/PowerboxServer";
	if(dbus.registerObject(path, &kpbserv, QDBusConnection::ExportAllSlots))
		cout << path.toStdString() << endl;

	else
	{
		cerr << "Failed to register " << path.toStdString() << ":"
		     << dbus.lastError().message().toStdString() << endl;

		return 1;
	}

	int retval = 0;
	while(!retval)
	{
		retval = app.exec();
		if(retval)
		{
			cerr << "Abnormal app.exec() result: " << retval << endl;
			return retval;
		}
	}

	return 0;
}

